const config = require('../config/config');
const request = require('request');
const {AppID, AppSecret} = require("../config/config").appInfo;
const cahce = require('./redis')
const redis = new cahce();
var getAccessTokenApi = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${AppID}&secret=${AppSecret}`;

module.exports = {
    AccessToken(){
        return new Promise((resolve, reject) =>{
            redis.get('wx_AccessToken').then(res=>{
                if (res == null) {
                    request(getAccessTokenApi, (err, response, body)=>{
                        if (err) console.log(err);
                        if(response.statusCode == 200){
                            redObj = JSON.parse(body);
                            if ('access_token' in redObj) {
                                redis.set('wx_AccessToken', redObj.access_token, 7200);
                                resolve(redObj.access_token);
                            }else{
                                console.log(body);
                            }
                        }else{
                            reject(response.statusCode);
                        }
                    })
                }else{
                    resolve(res);
                }
            })
        });
    },
}